package com.quad.innovators.salesease.common.utils;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SmUtil;
import com.quad.innovators.salesease.constants.SecurityConstants;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

import javax.crypto.KeyGenerator;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;

public class SmUtils {

    private static final String SM4_KEY = "e6ac1382ae601afb6436ece5325ef595";

    public static String sm3Encrypt(String text){
        return SmUtil.sm3(text);
    }

    public static String sm4Encrypt(String text){
        return sm4Encrypt(SM4_KEY, text);
    }

    public static String sm4Decrypt(String text){
        return sm4Decrypt(SM4_KEY, text);
    }

    public static String sm4Encrypt(String key, String text){
        return SmUtil.sm4(HexUtil.decodeHex(key)).encryptHex(text);
    }

    public static String sm4Decrypt(String key, String text){
        return SmUtil.sm4(HexUtil.decodeHex(key)).decryptStr(HexUtil.decodeHex(text));
    }

    public static String generateSM4Key() throws NoSuchAlgorithmException, NoSuchProviderException {
        Security.addProvider(new BouncyCastleProvider());
        KeyGenerator kg = KeyGenerator.getInstance("SM4", "BC");
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed("sales-ease-front0923".getBytes(Charset.defaultCharset()));
        kg.init(128, secureRandom);
        return  Hex.toHexString(kg.generateKey().getEncoded());

    }

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
        String cc = sm4Encrypt(SecurityConstants.FRONT_END_PASSWORD_ENCRYPT_KEY,"Aa694297");
        System.out.println(cc);
        String c = sm4Encrypt(cc);
        System.out.println(c);
        String d = sm4Decrypt(c);
        System.out.println(d);
        System.out.println(sm4Decrypt(SecurityConstants.FRONT_END_PASSWORD_ENCRYPT_KEY,d));
    }
}
